@echo off
setlocal

:: --- Configuration ---
set "PID_FILE=app.pid"
set "WINDOW_TITLE=aibox-pro-service"
:: ---------------------

echo Stopping the application...

if not exist "%PID_FILE%" (
    echo INFO: PID file not found. The application may not be running.
    
    :: As a fallback, try to find the process by its window title
    for /f "tokens=2" %%i in ('tasklist /v /fi "imagename eq javaw.exe" /fi "windowtitle eq %WINDOW_TITLE%*" /fo csv /nh') do (
        set "PID=%%~i"
    )
    
    if not defined PID (
        echo INFO: No running process found with title '%WINDOW_TITLE%'. Stop command finished.
        exit /b 0
    )
    
    echo INFO: Found running process with PID %PID% by window title.
) else (
    set /p PID=<"%PID_FILE%"
)

if not defined PID (
    echo ERROR: Could not determine the Process ID to stop.
    exit /b 1
)

echo Stopping process with PID: %PID%
taskkill /F /PID %PID% >nul 2>nul

if exist "%PID_FILE%" (
    del "%PID_FILE%"
)

echo Application stopped successfully.

endlocal
